import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-05-20
 * Time: 23:53
 */
public class LRUCache {
    // 自己定义node
    public static class Node{
        int key;
        int value;
        Node prev;
        Node next;

        public Node(int key,int value){
            this.value = value;
            this.key = key;
        }
    }

    // 定义默认变量
    private final int capacity;
    private final Node dummy = new Node(0,0);
    private HashMap<Integer,Node> hashMap = new HashMap<Integer,Node>();

    public LRUCache(int capacity) {
        this.capacity = capacity;
        dummy.prev = dummy;
        dummy.next = dummy;
    }

    public int get(int key) {
        Node node = getNode(key);
        if(node!=null){
            return node.value;
        }else{
            return -1;
        }
    }


    public void put(int key, int value) {
        Node node = getNode(key);
        if(node==null){
            Node newNode = new Node(key,value);
            pushFront(newNode);
            hashMap.put(key,newNode);
            if(hashMap.size()>capacity){
                Node backNode = dummy.prev;
                remove(backNode);
                hashMap.remove(backNode.key);
            }
        }else {
            node.value = value;
        }
    }


    private Node getNode(int key) {
        // 从哈希表中找，没找到就返回空
        if(!hashMap.containsKey(key)){
            return null;
        }
        Node node = hashMap.get(key);
        remove(node);

        pushFront(node);

        return node;

    }

    private void pushFront(Node node) {
        node.next = dummy.next;
        dummy.next.prev = node;
        node.prev = dummy;
        dummy.next = node;
    }

    private void remove(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
}
